package controllers;

import controllers.common.ControllerBase;
import dao.common.BrandManager;
import dao.common.CategoryManager;
import dao.common.ProductManager;
import dao.hibernate.BrandManagerHB;
import dao.hibernate.CategoryManagerHB;
import dao.hibernate.ProductManagerHB;
import models.exceptions.CreateEntityException;
import models.exceptions.GetEntityException;
import models.exceptions.GetEntityListException;
import models.shop.CategoryImageRecord;
import models.shop.Mail.ProductQuestionMessage;
import net.tanesha.recaptcha.ReCaptcha;
import net.tanesha.recaptcha.ReCaptchaImpl;
import net.tanesha.recaptcha.ReCaptchaResponse;
import play.data.validation.*;
import play.libs.WS;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Shop extends ControllerBase {
    private static CategoryManager categoryManager = new CategoryManagerHB();
    private static BrandManager brandManager = new BrandManagerHB();
    private static ProductManager productManager = new ProductManagerHB();
    public static void about() {
        setCache(3600);
        render();
    }

    public static void test(){
        render();
    }
    public static void contacts() throws GetEntityListException, IOException {
        setCache(3600);
        render();
    }

    public static void home() throws IOException {
        List<models.shop.Product> topProducts = productManager.listTopProducts(10);
        List<CategoryImageRecord> categoryImages = categoryManager.getCategoryImages();
        setCache(3600);
        render(topProducts, categoryImages);
    }

    //TODO: Refactor parameters
    public static void ask(@Valid ProductQuestionMessage pq) throws GetEntityListException, CreateEntityException, GetEntityException, IOException {
        ReCaptchaResponse captchaResponse = ValidateCaptcha();
        if (Validation.hasErrors() || !captchaResponse.isValid()) {
            params.flash();
            Validation.keep();
            if (!captchaResponse.isValid()){
                flash.error("Код проверки не верный");
            } else {
            flash.error("Shop.contacts.requiredall");
            }
            contacts();
        } else {

            notifiers.Mails.askQuestion(pq);
            flash.success("Shop.contacts.sendsuccessful");
            contacts();
        }
    }



    public static void favicon() throws FileNotFoundException {
        File icon = play.Play.getFile("public/images/favicon.png");
        renderCachedBinary(icon, "2h");
    }

    public static void robots() throws FileNotFoundException {
        File robotsText = play.Play.getFile("public/robots.txt");
        renderCachedBinary(robotsText, "2h");
    }

    public static void unknown(){
        error(404, "page not found");
    }

}
